-- ============================================
-- SNOUB CASINO - Menu d'accueil
-- Nécessite : Advanced Computer + Advanced Monitor (couleur)
-- Astuce : pour revenir ici depuis un jeu, appuie sur
--          Ctrl+T (terminer) sur l'ordinateur.
-- ============================================

local balance = dofile("balance.lua")

local GAMES = {
    { label = "Machine a sous",     file = "slot_machine" },
    { label = "Roulette",           file = "roulette_visuelle" },
    { label = "Blackjack",          file = "blackjack" },
    { label = "Shoot le Zenh",      file = "shoot_le_zenh" },
    { label = "Crash / Fusee",      file = "crash_fusee" },
    { label = "Plinko",             file = "plinko" },
    { label = "Roue de la fortune", file = "roue_fortune" },
    { label = "Stop la barre",      file = "stop_la_barre" },
    { label = "Poker video",        file = "poker_video" },
}

local mon = peripheral.find("monitor")
if not mon then
    error("Aucun monitor trouve ! Colle un Advanced Monitor a cote du computer.")
end

mon.setTextScale(0.5)
local prevTerm = term.redirect(mon)
local w, h = term.getSize()

local function centerText(y, text, textColor, bgColor)
    term.setBackgroundColor(bgColor or colors.black)
    term.setTextColor(textColor or colors.white)
    local x = math.floor((w - #text) / 2) + 1
    term.setCursorPos(x, y)
    term.write(text)
end

local buttons = {}

local function drawMenu()
    local points = balance.load()

    term.setBackgroundColor(colors.black)
    term.clear()
    centerText(1, "$$$$$$$$$$$$$$$$$$$$$$$$$$$$", colors.green)
    centerText(2, "SNOUB CASINO", colors.yellow)
    centerText(3, "$$$$$$$$$$$$$$$$$$$$$$$$$$$$", colors.green)
    centerText(5, "Solde : " .. points .. " points", colors.lime)

    buttons = {}
    local startY = 7
    local btnW = math.min(w - 4, 34)
    local x1 = math.floor((w - btnW) / 2) + 1
    local x2 = x1 + btnW - 1

    for i, game in ipairs(GAMES) do
        local y = startY + (i - 1) * 2
        term.setBackgroundColor(colors.gray)
        term.setTextColor(colors.white)
        for x = x1, x2 do
            term.setCursorPos(x, y)
            term.write(" ")
        end
        local lx = x1 + math.floor((btnW - #game.label) / 2)
        term.setCursorPos(lx, y)
        term.write(game.label)
        buttons[i] = { x1 = x1, x2 = x2, y = y, file = game.file }
    end

    centerText(startY + #GAMES * 2 + 1, "Ctrl+T dans un jeu pour revenir ici", colors.lightGray)
end

-- === PROGRAMME PRINCIPAL ===
drawMenu()

while true do
    local event, side, x, y = os.pullEvent("monitor_touch")
    local chosen = nil
    for _, btn in ipairs(buttons) do
        if x >= btn.x1 and x <= btn.x2 and y == btn.y then
            chosen = btn.file
            break
        end
    end

    if chosen then
        term.redirect(prevTerm)
        local ok, err = pcall(shell.run, chosen)
        term.redirect(mon)
        drawMenu()
    end
end
